<?php

namespace App\Http\Controllers\Logistics;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
use Config;

class KdNiaoController extends Controller
{
    protected $appkey;
    protected $ebusinessid;
    protected $api_url;
    protected $ebusiness_url;

    public function __construct()
    {
        $this->ebusinessid = Config::get('zgssystem.kdn_ebusinessid');
        $this->appkey = Config::get('zgssystem.kdn_ebusinessid');
        $this->api_url = 'http://api.kdniao.cc/api/dist';
        $this->ebusiness_url = 'http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx';
    }

    /**
     * 订阅物流信息接口
     * 在写入订单的时候发起
     * Json方式
     */
    public function getTrack($name,$code){
        $data['ShipperCode'] = $name;
        $data['LogisticCode'] = $code;
        $requestData = json_encode($data);
        $datas = array(
             'EBusinessID' => $this->ebusinessid,
             'RequestType' => '1008',
             'RequestData' => urlencode($requestData),
             'DataType' => '2',
        );
        $datas['DataSign'] = $this->encrypt($requestData, $this->appkey);
        $result = $this->sendPost($this->api_url, $datas);
        //根据公司业务处理返回的信息..
        $re = json_decode($result,true);
        if(true === $re['Success']){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 订阅推送 回调地址
     */
    public function getTrackCallback(Request $request)
    {
        $data = $request->all();
        $res = json_decode($data['RequestData'],true);
        $info = $res ? $res['Data'] : [];

        //物流信息写入数据库
        $this->updateTrackData($info);

        $re = [
             "EBusinessID"  => $this->ebusinessid,
             "UpdateTime"   => date("Y-m-d H:i:s"),
             "Success"      => true,
        ];
        return json_encode($re);
    }

    /**
     * 订阅推送 物流信息写入数据库
     */
    protected function updateTrackData($data)
    {
        //根据项目定义物流的三个字段，1：物流公司编号，2：物流单号，3:物流信息，4：更新时间
        $tablename = 'logistics_callback';
        $field = ['kdn_company_code','kdn_logistics_num','kdn_logistics_track','update_time'];
        foreach($data as $val){
            DB::table($tablename)->where([$field[0]=>strtoupper($val['ShipperCode']),$field[1]=>strtoupper($val['LogisticCode'])])->update([$field[2]=>json_encode($val['Traces']),$field[3]=>time()]);
        }
    }


    /**
     * 及时查询物流接口
     * Json方式
     * 每日3000次调用
     */
    public function getTimely($name,$code)
    {
        $data['ShipperCode'] = $name;
        $data['LogisticCode'] = $code;
        $requestData = json_encode($data);
        $datas = array(
             'EBusinessID' => $this->ebusinessid,
             'RequestType' => '1002',
             'RequestData' => urlencode($requestData) ,
             'DataType' => '2',
        );
        $datas['DataSign'] = $this->encrypt($requestData, $this->appkey);
        $infolist = $this->sendPost($this->ebusiness_url, $datas);
        $infoarr = json_decode($infolist, true);
        return $infoarr;
    }

    /**
     * post提交数据
     * @param  string $url 请求Url
     * @param  array $datas 提交的数据
     * @return url响应返回的html
     */
    protected function sendPost($url, $datas) {
        $temps = array();
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);
        }
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        if(empty($url_info['port']))
        {
            $url_info['port']=80;
        }
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader.= "Host:" . $url_info['host'] . "\r\n";
        $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader.= "Connection:close\r\n\r\n";
        $httpheader.= $post_data;
        $fd = fsockopen($url_info['host'], $url_info['port']);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets.= fread($fd, 128);
        }
        fclose($fd);
        return $gets;
    }

    /**
     * 电商Sign签名生成
     * @param data 内容
     * @param appkey Appkey
     * @return DataSign签名
     */
    protected function encrypt($data, $appkey) {
        return urlencode(base64_encode(md5($data.$appkey)));
    }
}